<!DOCTYPE HTML>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport"
        content="maximum-scale=1.0, minimum-scale=1.0, user-scalable=0, initial-scale=1.0, width=device-width" />
    <meta name="format-detection" content="telephone=no, email=no, date=no, address=no">
    <title>Hello APP</title>
    <link rel="stylesheet" type="text/css" href="../css/api.css" />
    <style>
        label {
            margin: 10px;
            font-size: 24px;
        }

        ul {
            margin-bottom: 10px;
        }

        ul li {
            margin: 5px 10px;
            padding: 5px;
            color: #000;
            word-wrap: break-word;
        }

        button {
            margin: 10px 10px;
        }
    </style>
</head>

<body>
    <label>Hello APP111</label>
    <div id='sys-info'></div>
    <div>
        <div>用户ID：<input type="text" style="border-bottom: 1px solid gray;" id="userId" /></div>
        <button type="button" onclick="enterRoom()">进入房间</button>
        <button type="button" onclick="exitRoom()">退出房间</button>
        <button type="button" onclick="dismissRoom()">解散房间</button>
    </div>
</body>
<script type="text/javascript" src="../script/api.js"></script>
<script type="text/javascript">
    var tencentTRTCCall;
    var roomId = "100120";

    apiready = function () {
        tencentTRTCCall = api.require('tencentTRTC');

        var ver = api.version;
        var sType = api.systemType;
        var sVer = api.systemVersion;
        var model = api.deviceModel;
        var name = api.deviceName;
        var cType = api.connectionType;
        var winName = api.winName;
        var winWidth = api.winWidth;
        var winHeight = api.winHeight;
        var frameName = api.frameName || '';
        var frameWidth = api.frameWidth || '';
        var frameHeight = api.frameHeight || '';

        var str = '<ul>';
        str += '<li>引擎版本信息: ' + ver + '</li>';
        str += '<li>系统类型: ' + sType + '</li>';
        str += '<li>系统版本: ' + sVer + '</li>';
        str += '<li>设备型号: ' + model + '</li>';
        str += '<li>设备名称: ' + name + '</li>';
        str += '<li>网络状态: ' + cType + '</li>';
        str += '<li>主窗口名字: ' + winName + '</li>';
        str += '<li>主窗口宽度: ' + winWidth + '</li>';
        str += '<li>主窗口高度: ' + winHeight + '</li>';
        str += '<li>子窗口名字: ' + frameName + '</li>';
        str += '<li>子窗口宽度: ' + frameWidth + '</li>';
        str += '<li>子窗口高度: ' + frameHeight + '</li>';
        str += '</ul>';
        $api.byId('sys-info').innerHTML = str;

        tencentTRTCCall.setTRTCListener({}, function (ret, err) {
            if (ret) {
                const action = ret.action;
                switch (action) {
                    case 'error':
                        console.log('错误回调', JSON.stringify(ret.error));
                        break;
                    case 'warning':
                        console.log('警告事件', JSON.stringify(ret.warning));
                        break;
                    case 'enterRoom':
                        console.log('进入房间事件', JSON.stringify(ret.enterRoom))
                        var result = ret.enterRoom.result;
                        if (result > 0) {
                            console.log(`进入房间成功,耗时：${result}ms`);
                            // 开启本地语音
                            tencentTRTCCall.startLocalAudio({});
                            // 开启本地画面采集
                            tencentTRTCCall.startLocalPreview({
                                rect: {
                                    x: 0,
                                    y: 0,
                                    width: 300,
                                    height: 300
                                }
                            }, function (ret, err) {
                                console.log('开启本地画面采集方法回调数据', JSON.stringify(ret), JSON.stringify(err));
                            });
                        } else {
                            console.log(`进入房间失败,错误码：${result}`);
                        }
                        break;
                    case 'remoteUserEnterRoom':
                        console.log('有用户加入当前房间', JSON.stringify(ret.remoteUserEnterRoom))
                        break;
                    case 'remoteUserLeaveRoom':
                        console.log('有用户离开当前房间', JSON.stringify(ret.remoteUserLeaveRoom))
                        // 如果离开房间的是发起人，则自动退出房间
                        var userId = ret.remoteUserLeaveRoom.userId;
                        if (userId == 'jackxie') {
                            exitRoom();
                        }
                        break;
                    case 'userVideoAvailable':
                        console.log('远端用户是否存在可播放的主路画面事件', JSON.stringify(ret.userVideoAvailable));
                        // 用户标识，字符串
                        var userId = ret.userVideoAvailable.userId;
                        // 画面是否开启，布尔类型
                        var available = ret.userVideoAvailable.available;
                        if (userId) {
                            console.log(`用户[${userId}]的视频是否开启:${available}`);
                            if (available) {
                                // 开始显示用户userId的视频画面
                                tencentTRTCCall.startRemoteView({
                                    rect: {
                                        x: 0,
                                        y: 305,
                                        w: 300,
                                        h: 300,
                                    },
                                    remoteUid: userId,
                                });
                            } else {
                                // 停止显示用户userId的视频画面
                                tencentTRTCCall.stopRemoteView({
                                    remoteUid: userId
                                });
                            }
                        } else {
                            console.log('自己的视频');
                        }
                        break;
                    case 'userAudioAvailable':
                        console.log('远端用户是否存在可播放的音频数据事件', JSON.stringify(ret.userAudioAvailable));
                        // 用户标识，字符串
                        var userId = ret.userAudioAvailable.userId;
                        // 声音是否开启，布尔类型
                        var available = ret.userAudioAvailable.available;
                        if (available) {
                            // 继续接收远端用户音频流
                            tencentTRTCCall.muteRemoteAudio({
                                remoteUid: userId,
                                mute: false
                            });
                        } else {
                            // 暂停接收远端用户音频流
                            tencentTRTCCall.muteRemoteAudio({
                                remoteUid: userId,
                                mute: true
                            });
                        }
                        if (userId) {
                            console.log(`用户[${userId}]的音频是否开启:${available}`);
                        } else {
                            console.log('自己的音频');
                        }
                        break;
                    case 'exitRoom':
                        console.log('退出房间事件', JSON.stringify(ret.exitRoom));
                        var reason = ret.exitRoom.reason;
                        if (reason == 0) {
                            console.log('用户主动退出房间');
                        } else if (reason == 1) {
                            console.log('用户被踢出房间');
                        } else if (reason == 2) {
                            console.log('房间被解散，用户退出');
                        }
                        // 停止显示所有远端视频画面，同时不再拉取远端用户的视频数据流
                        tencentTRTCCall.stopAllRemoteView({});
                        // 停止本地音频
                        tencentTRTCCall.stopLocalAudio({});
                        // 停止本地视频采集
                        tencentTRTCCall.stopLocalPreview({
                        }, function (ret, err) {
                            console.log('停止本地画面采集方法回调数据', JSON.stringify(ret), JSON.stringify(err));
                        });
                        break;
                    default:
                        console.log('未知的或暂未处理的事件', JSON.stringify(ret));
                }
            }
            if (err) {
                console.log('模块返回错误信息', JSON.stringify(err));
            }
        });

    };

    /**
     * 获取用户进房票据
     * 
     * @param userId String
     * @return 返回票据 String
     */
    function getUserSig(userId) {
        return new Promise((resolve, reject) => {
            api.ajax({
                url: 'http://125.67.207.6:12080/tencent-trtc/userSig',
                method: 'get',
                data: {
                    values: {
                        userId: userId
                    }
                },
                dataType: 'text',
            }, function (ret, err) {
                console.log('获取用户进房票据', JSON.stringify(ret), JSON.stringify(err));
                if (ret) {
                    resolve(ret);
                } else {
                    reject(err);
                }
            })
        });
    }

    /**
     * 进入房间
     */
    async function enterRoom() {
        var userId = $api.byId("userId").value;
        if (!userId) {
            api.alert({ msg: '请先输入用户ID' });
            return;
        }
        var userSig = await getUserSig(userId);
        if (userSig) {
            tencentTRTCCall.enterRoom({
                appId: 1400785727,
                userId: userId,
                roomId: roomId,
                userSig: userSig,
            }, function (ret, err) {
                console.log('进入房间回调数据', JSON.stringify(ret), JSON.stringify(err));
            });
        }
    }

    /**
     * 退出房间
     */
    function exitRoom() {
        tencentTRTCCall.exitRoom({
        }, function (ret, err) {
            console.log('退出房间回调数据', JSON.stringify(ret), JSON.stringify(err));
        });
    }

    /**
     * 解散房间（只有发起人可解散房间）
     *  
     */
    function dismissRoom() {
        return new Promise((resolve, reject) => {
            api.ajax({
                url: 'http://125.67.207.6:12080/tencent-trtc/dismissRoom',
                method: 'get',
                data: {
                    values: {
                        roomId: roomId
                    }
                },
                dataType: 'text',
            }, function (ret, err) {
                console.log('解散房间接口返回数据', JSON.stringify(ret), JSON.stringify(err));
                if (ret) {
                    resolve(ret);
                } else {
                    reject(err);
                }
            })
        });
    }
</script>

</html>